package com.wx.io;

import java.io.*;
import java.net.Socket;

/**
 * Socket Client
 * @author wangxun
 * @version 1.0
 * @description: Socket Client
 * @date 2020/12/30 4:16 下午
 */
public class SocketClient {
    public static void main(String[] args) throws IOException {
        Socket client = new Socket("127.0.0.1",9999);
        client.setSendBufferSize(20);
        // 是否不优化Tcp
        //client.setTcpNoDelay(false);
        OutputStream out = client.getOutputStream();

        // 接收返回
        InputStream clientInputStream = client.getInputStream();
        new Thread(()->{
            while(true){
                byte[] bytes = new byte[40];
                try {
                    int read = clientInputStream.read(bytes);
                    if(read>0){
                        System.out.println(new String(bytes));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        // 读取输入流
        InputStream in = System.in;
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));

        while (true){
            String dataLine = reader.readLine();
            // readLine 读取到换行符才去停止阻塞, 服务端readLine也只有读到换行符才会进行接收

            if (dataLine != null) {
                dataLine+="\n";
                byte[] bytes = dataLine.getBytes();
                for (byte b : bytes) {
                    out.write(b);
                }
                out.flush();
            }
        }
    }
}
